package com.lzz.controller;

import com.lzz.entity.FileInfo;
import com.lzz.entity.UserBack;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

// @RestController注解相当于@ResponseBody + @Controller合在一起使用
// 使用RestController注解Controller,则Controller中方法无法返回视图页面（jsp，html）配置的视图解析器不起作用
// @RestController注解可以返回Json数据

/**
 *
 * @author zhenzhen
 * @date 2018-12-03 下午7:32
 */
@RestController
public class TestController {
    @GetMapping("/helloword")
    public String helloword(){
        return "hellowordsss";
    }

    @GetMapping("/testUser")
    public UserBack testUser() {
        UserBack user = new UserBack(1, "高圆圆", "jack123", new Date());
        return user;
    }

    @GetMapping("/errorTest")
    public String errorTest(){
        int i = 2 / 0;
        return "errorTest";
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/fileupload")
    public FileInfo upload(@RequestParam(value = "file") MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        String localPath = "/home/zhenzhen/tmp/springboot";
        File localFile = new File(localPath, file.getOriginalFilename());
        file.transferTo(localFile);
        FileInfo fileInfo = new FileInfo(localFile.getAbsolutePath());
        return fileInfo;
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        String localPath = "/home/zhenzhen/tmp/springboot";
        File file = new File(localPath, id+".jpg");
        try {
            InputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + id + ".jpg");
            IOUtils.copy(inputStream, outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
